package com.chandankumar.gaejsimplesite.gae.db;

import java.util.List;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;

import org.springframework.stereotype.Repository;

import com.chandankumar.gaejsimplesite.model.Page;
@Repository
public class PageServiceImpl implements PageService{
	PersistenceManager pm = null;
	@Override
	public Page save(Page page) {
		try {
			pm= PMF.get().getPersistenceManager();
			page = pm.makePersistent(page);
		} finally {
			pm.close();
		}
		return page;
	}

	@Override
	public Page update(Page page) {
		Page existingEntity = null;
		try {
			pm= PMF.get().getPersistenceManager();
			existingEntity = pm.makePersistent(page);
			existingEntity.setTitle(page.getTitle());
			existingEntity.setContent(page.getContent());
		} finally {
			pm.close();
		}
		return existingEntity;
	}

	@Override
	public Page findByKey(Long key) {
		Page detachedCopy=null, object=null;
		try{
			pm= PMF.get().getPersistenceManager();
			object = pm.getObjectById(Page.class,key);
			detachedCopy = pm.detachCopy(object);
		}catch (JDOObjectNotFoundException e) {
			return null;
		} 
		finally {
			pm.close();
		}
		return detachedCopy;
		
	}
	
	@Override
	public void findByTitle(String title) {
		// TODO Auto-generated method stub
		
	}
	
	public List<Page> getAll(){
		List<Page> detachedCopy=null, object=null;
		try {
			String query = "select from " + Page.class.getName();
			pm = PMF.get().getPersistenceManager();
			object = (List<Page>)pm.newQuery(query).execute();
			object.size();
			// detachedCopy = pm.detachCopy(object);
			return object;
		} finally {
			pm.close();
		}
	}
}
